//
//  MyDownloadViewController.m
//  Estate
//
//  Created by heyong on 16/6/25.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "MyDownloadViewController.h"
#import "downLoadPdfCell.h"
#import "downModel.h"
#import "MJPhotoBrowser.h"
#import "DownLoadController.h"

@interface MyDownloadViewController ()<DownLoadControllerDelegate>


@end

@implementation MyDownloadViewController
-(NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray=[NSMutableArray array];
    }
    return _dataArray;
}

-(UITableView *)tableView{
    if(_tableView==nil){
        _tableView=[[UITableView alloc]initWithFrame:self.view.bounds];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.tableFooterView=[[UIView alloc]init];
    }
    return _tableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title=@"我的下载";
    [self.view addSubview:self.tableView];
    
    [self setData];
    self.view.backgroundColor=[UIColor whiteColor];
    
    if (self.isSearch) {
        //搜索下载
        self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"sousuo_1"] style:UIBarButtonItemStyleDone target:self action:@selector(download)];
    }
}
#pragma mark- 跳转至下载
- (void)download{
     DownLoadController *downCtr = [[DownLoadController alloc]init];
    downCtr.delegate = self;
    downCtr.oldDataArray = self.dataArray;
    [self.navigationController pushViewController:downCtr animated:YES];
}
#pragma mark DownLoadController 下载完成代理方法
-(NSArray *)didDownComplete{
    [self setData];
    [self.tableView reloadData];
    return self.dataArray;
}
-(void)setData{
    //遍历沙盒里的文件
    [self.dataArray removeAllObjects];

    NSString *fullPath=DEF_FILE_PDF_PATH;
    NSLog(@"%@",fullPath);
    //文件夹操作
    NSFileManager*fileManager = [NSFileManager defaultManager];
    //获取本地Documents路径
    NSArray*fileList = [[NSArray alloc]init];
    //得到目录下文件名
    fileList=[fileManager contentsOfDirectoryAtPath:fullPath error:nil];
    for(int i=0;i<fileList.count;i++){
        //得到路径
        NSString *tempPath=[fullPath stringByAppendingString:[NSString stringWithFormat:@"/%@",fileList[i]]];
        downModel *model=[[downModel alloc]init];
        if([fileList[i] isEqualToString:@".DS_Store"]){
            continue;
        }
        NSString *title =fileList[i];
        NSArray *titles =  [title componentsSeparatedByString:@"+"];
        model.pdfId=tempPath;
        model.id = [titles firstObject];
        model.title= [titles lastObject];
        model.type= [[model.title componentsSeparatedByString:@"."]lastObject];
        [self.dataArray addObject:model];
    }
}

#pragma mark-UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier=@"downCell";
    downLoadPdfCell *cell;
    cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if(!cell){
        cell=[[downLoadPdfCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    [cell.downBtn setImage:[UIImage imageNamed:@"chakan_1"] forState:UIControlStateNormal];
    downModel *downMo=self.dataArray[indexPath.row];
    [cell setTitleContent:downMo.title];
    cell.detailBlick=^{
        PdfDetailViewController *detail=[[PdfDetailViewController alloc] init];
        detail.filePath=downMo.pdfId;
        if( [downMo.type isEqualToString:@"pdf"]||[downMo.type isEqualToString:@"PDF"]){
            detail.fileType=@"pdf";
            [self.navigationController pushViewController:detail animated:YES];
        }else{
            [self clickImageView:downMo.pdfId];
            detail.fileType=@"png";
            
        }
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    downModel *model= self.dataArray[indexPath.row];
    return  [downLoadPdfCell cellContentHeight:model.title];
}

//点击图片放大显示
-(void)clickImageView:(NSString *)filePath{
    NSMutableArray *photos = [NSMutableArray array];
    
    MJPhoto *photo = [[MJPhoto alloc] init];
    photo.image = [UIImage imageWithContentsOfFile:filePath];
    [photos addObject:photo];
    
    MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
    browser.photos = photos;
    browser.showSaveBtn = NO;
    [browser show];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
#pragma mark 设置可以进行编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
        return YES;
}

#pragma mark 设置编辑的样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

#pragma mark 设置处理编辑情况
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // 更新数据
        downModel *downMo=self.dataArray[indexPath.row];
        [self deleteFile:[NSString stringWithFormat:@"%@+%@",downMo.id,downMo.title]];
        [self.dataArray removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView reloadData];
    }
    
}
//删除文件
-(void)deleteFile:(NSString *)fileName{
    
    
    NSString *documentsPath = DEF_FILE_PDF_PATH;
    
    NSString *fileDirectory = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@",fileName]];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL res=[fileManager removeItemAtPath:fileDirectory error:nil];
    
    if (res) {
        
        NSLog(@"文件删除成功");
        
    }else
        NSLog(@"文件删除失败");
    
    NSLog(@"文件是否存在: %@",[fileManager isExecutableFileAtPath:fileDirectory]?@"YES":@"NO");
    
}

/*
 #pragma mark - Navigation
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
